package com.solution.util;

import java.net.URL;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

import com.solution.constant.FileInitializationConstants;
import com.solution.dao.DAO;

/**
 * This is the hibernate utility class used for getting 
 * the session factory after loading the configuration file.
 * @author Piyush.Mittal
 *
 */
public class HibernateUtil {
	/**
	 * Logger instance.
	 */
	private static Logger log = Logger.getLogger(HibernateUtil.class.getName());
	/**
	 * Singleton object for sessionFactory.
	 */
	private static final SessionFactory factory = prepareSessionFactory();
	
	/**
	 * Loads the configuration file and returns the sessionFactory object.
	 * @return
	 */
	private static SessionFactory prepareSessionFactory(){
		SessionFactory sessionFactory = null;
		try{
			log.info("Configuring Hibernate session factory");
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			url = DAO.class.getResource(FileInitializationConstants.HIBERNATE_CONF_FILE);
			sessionFactory = new AnnotationConfiguration().configure(url).buildSessionFactory();
			log.info("Hibernate session factory configured");
		}
		catch(Throwable t){
			log.fatal("Exception occured while configuring hibernate.",t);
			System.exit(0);
		}
		return sessionFactory;
	}
	
	/**
	 * Returns the session factory object.
	 * @return
	 */
	public static SessionFactory getSessionFactory(){
		return factory;
	}
 
	/**
	 * Returns the current session or creates a new session if no session exists.
	 * @return
	 */
	public static Session getCurrentSession(){
		if(factory.getCurrentSession().isOpen()){
			return factory.getCurrentSession();
		}
		return factory.openSession();
	}
 
	/**
	 * Creates a new session.
	 * @return
	 */
	public static Session openSession(){
		return factory.openSession();
	}

}
